package eu.floranet.arquivo.model.persistence.link;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import eu.floranet.arquivo.model.persistence.exception.EmptyLinkEntity;
import eu.floranet.arquivo.model.persistence.exception.EmptyLinkFile;
import eu.floranet.arquivo.model.persistence.exception.EmptyLinkProperties;
import eu.floranet.arquivo.model.persistence.exception.LinkException;

public class PersistenceLinkEntityManager {

	protected EntityManagerFactory emf = null;
	protected EntityManager em = null;
	
	public PersistenceLinkEntityManager() throws EmptyLinkEntity {
		super();
		try {
			checkPersistenceLinkManager();
		} catch (EmptyLinkEntity e) {
			throw new EmptyLinkEntity(e.getMessage(), e.getCause());
		} catch (EmptyLinkProperties e) {
			throw new EmptyLinkEntity(e.getMessage(), e.getCause());
		} catch (EmptyLinkFile e) {
			throw new EmptyLinkEntity(e.getMessage(), e.getCause());
		} catch (LinkException e) {
			throw new EmptyLinkEntity(e.getMessage(), e.getCause());
		}
	}

	protected void checkPersistenceLinkManager() throws EmptyLinkEntity, EmptyLinkProperties, EmptyLinkFile, LinkException{
		if(PersistenceLinkEntityHandler.persistenceLinkManager != null){
			if(!PersistenceLinkEntityHandler.persistenceLinkManager.isPropertiesMapEmpty()){
				this.emf = Persistence.createEntityManagerFactory(
						PersistenceLinkEntityHandler.getNameEntityManagerFactory(), PersistenceLinkEntityHandler.persistenceLinkManager.getPropertiesMap());
			} else {
				PersistenceLinkEntityHandler.persistenceLinkManager.readPersistenceProperties();
				this.emf = Persistence.createEntityManagerFactory(
						PersistenceLinkEntityHandler.getNameEntityManagerFactory(), PersistenceLinkEntityHandler.persistenceLinkManager.getPropertiesMap());
			}
		} else {
			throw new EmptyLinkEntity(
					"Dados de configuração nulos.",
					new Throwable(
							"\nClass: eu.floranet.arquivo.model.persistence.link.PersistenceLinkEntityManager"+
							"\nMétodo: checkPersistenceLinkManager()"+
							"\nLinha: 18"));
		}
	}
	
	public void initEntityManager(){
		if(this.emf != null){
			this.em = this.emf.createEntityManager();
		} else {
			
		}
	}
	
	public void cleanUpClosedEMF() {
		if (this.emf != null && !this.emf.isOpen()) {
			this.emf = null;
		} else if (this.emf != null && this.emf.isOpen()) {
			this.emf.close();
			this.emf = null;
		}
	}
}
